﻿using System;
using System.Collections.Generic;
using System.Web;
using SubSonic;


namespace TCMSystem
{
    public class CustomMenuHelper
    {
        private static List<CustomMenu> _customMenus;

        public static void UpdateCustomMenus()
        {
            _customMenus = null;
        }

        public static List<CustomMenu> GetCustomMenus()
        {
            if (_customMenus == null)
            {
                TblMstMenuCollection items = new Select().From<TblMstMenu>()
                    .OrderAsc(TblMstMenu.SortIndexColumn.ColumnName)
                    .ExecuteAsCollection<TblMstMenuCollection>();

                List<CustomMenu> newMenus = new List<CustomMenu>();
                ResolveMenuCollection(items, newMenus, 0, 0);

                _customMenus = newMenus;
            }

            return _customMenus;
        }

        private static int ResolveMenuCollection(TblMstMenuCollection oldMenus, List<CustomMenu> newMenus, int parentId, int level)
        {
            int count = 0;
            foreach (TblMstMenu menu in oldMenus)
            {
                if (menu.ParentMenuId == parentId)
                {
                    count++;

                    CustomMenu my = new CustomMenu();
                    newMenus.Add(my);
                    my.TreeLevel = level;
                    my.Id = menu.Id;
                    my.ImageUrl = menu.ImageUrl;
                    my.Name = menu.Name;
                    my.Title = menu.Title;
                    my.NavigateUrl = menu.NavigateUrl;
                    my.ParentId = menu.ParentMenuId;
                    my.Remark = menu.Remark;
                    //my.IsModule = menu.IsModule;
                    my.SortIndex = menu.SortIndex;


                    level++;
                    int childCount = ResolveMenuCollection(oldMenus, newMenus, menu.Id, level);
                    if (childCount == 0)
                    {
                        my.IsTreeLeaf = true;
                    }
                    level--;
                }
            }

            return count;
        }

    }
}
